package demo.engine.template;

import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;
import org.junit.Test;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;
import org.xml.sax.SAXException;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;

public class JsoupDemo {


    /**
     * 将HTML呈现为图像
     *
     * @param htmlContent
     * @param width       Target width, in pixels, for the image; required to provide horizontal bounds for the layout.
     * @return
     */
    public static BufferedImage renderHtmlToImage(String htmlContent, int width) {
        Document document = Jsoup.parse(htmlContent);
        document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
        document.outputSettings().escapeMode(Entities.EscapeMode.xhtml);

        W3CDom w3cDom = new W3CDom();
        org.w3c.dom.Document doc = w3cDom.fromJsoup(document);

        Java2DRenderer renderer = new Java2DRenderer(doc, 800);
        return renderer.getImage();
    }

    /**
     * 保存图片
     *
     * @param image
     * @param filePath
     * @throws IOException
     */
    public static void saveImageToFile(BufferedImage image, String filePath) throws IOException {
        File file = new File(filePath);
        try (OutputStream os = Files.newOutputStream(file.toPath());) {
            FSImageWriter imageWriter = new FSImageWriter();
            imageWriter.write(image, os);
        }
    }

    @Test
    public void testHtmlTable() throws IOException, SAXException {
        String[] header = {"报警类型", "分组", "域名", "实例"};
        List<String[]> data = Arrays.asList(
                new String[]{"流量下跌", "wap", "linkeye.ximalaya.com", "10.10.10.10"},
                new String[]{"5xx报警", "xdcs", "xdcs-collector.ximalaya.com", "sh-nh-b24-302-n11-nginx-88-232"}
        );
        StringBuilder html = MarkdownDemo.htmlTable(header, data);
        System.out.println(html);

        String htmlFilePath = "/Users/xmly/Documents/tmp/test.html";
        MarkdownDemo.markdown2HtmlFile(html.toString(), htmlFilePath);
        BufferedImage image = renderHtmlToImage(html.toString(), 800);

        String imagePath = "/Users/xmly/Documents/tmp/test.png";
        saveImageToFile(image, imagePath);
        System.out.println("OK");
    }

}
